<template>
  <div class="tabBox">
    <!-- <input
      ref="PDAScan"
      v-model="PDACode"
      @focus.prevent="blurscan"
      @blur="$refs.PDAScan.focus()"
      @input="inputscan"
      style="position:fixed; top:-0.1rem;opacity:0;width:0.1rem"
    /> -->
    <van-tabbar class="tabbar" :value="current" @change="go">
      <van-tabbar-item v-for="item in tabs" :key="item.label">
        <div class="item flex-column align">
          <img
            :src="path === item.path ? item.selectedIcon : item.icon"
            alt=""
            :class="{
              icon: true,
              iconcenter: item.path == '/initiateApplication',
            }"
          />
          <span :class="['tabLabel', { selected: path === item.path }]">{{
            item.label
          }}</span>
        </div>
      </van-tabbar-item>
    </van-tabbar>
    <!-- 浏览器扫码组件 -->
    <qrcode
      :qrcode="codeForm.qrcode"
      :showClose="codeForm.showClose"
      v-show="codeForm.qrcode"
      :camera="camera"
      :torchActive="torchActive"
      @switchCamera="switchCamera"
      @ClickFlash="ClickFlash"
      @turnCameraOff="turnCameraOff"
      @onDecode="onDecode"
      @onInit="onInit"
    />
    <!-- 扫码去向选择 -->
    <van-overlay :show="showType" @click="showType = false">
      <div class="btn-wrapper" @click.stop>
        <div class="type-btn">
          <div
            class="typebs"
            v-for="(t, i) in codeTypes"
            :key="i"
            @click="goType(t)"
          >
            {{ t.name }}
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
// import VueCordova from 'vue-cordova'
// import Vue from 'vue'

import * as dd from "dingtalk-jsapi";
import { queryBatchTaskReportList } from "@/api/mobile";
import { workOrderListProduce,produceOrderReportWorkWorkbenchProduce } from "@/api/productionApply";
const tabbar = {
  home: require("@/assets/tabbar/home.png"),
  home_selected: require("@/assets/tabbar/home_selected.png"),
  application: require("@/assets/tabbar/application.png"),
  application_selected: require("@/assets/tabbar/application_selected.png"),
  sponsor: require("@/assets/tabbar/sponsor.png"),
  report: require("@/assets/tabbar/report.png"),
  report_selected: require("@/assets/tabbar/report_selected.png"),
  mine: require("@/assets/tabbar/mine.png"),
  mine_selected: require("@/assets/tabbar/mine_selected.png"),
};
export default {
  name: "TabBar",
  components: { qrcode: () => import("@/components/scanCode") },
  data() {
    return {
      tabs: [
        {
          label: "首页",
          path: "/dashboard/analysis",
          icon: tabbar.home,
          selectedIcon: tabbar.home_selected,
        },
        {
          label: "应用",
          path: "/application",
          icon: tabbar.application,
          selectedIcon: tabbar.application_selected,
        },
        // {
        //   label: "",
        //   path: "/initiateApplication",
        //   icon: tabbar.sponsor,
        //   selectedIcon: tabbar.sponsor,
        // },
        // {
        //   label: "报表",
        //   path: "/report",
        //   icon: tabbar.report,
        //   selectedIcon: tabbar.report_selected,
        // },
        {
          label: "我的",
          path: "/mine",
          icon: tabbar.mine,
          selectedIcon: tabbar.mine_selected,
        },
      ],
      codeForm: {
        qrcode: false,
        showClose: false,
      },
      torchActive: true,
      camera: "off",
      showType: false, // 扫码去向选择遮罩层
      codeTypes: [],
      orderType: [
        {
          name: "新建报工",
          EntityType: "workOrder",
          path: "/newReportForm",
        },
        {
          name: "生产入库",
          EntityType: "workOrder",
          path: "/inventoryOrderForm",
        },
        {
          name: "生产出库",
          EntityType: "workOrder",
          path: "/outboundOrderForm",
        },
      ],
     goodsType:[
        {
          name: "新建入库",
          EntityType: "goods",
          path: "/inventoryOrderForm",
        },
        {
          name: "新建出库",
          EntityType: "goods",
          path: "/outboundOrderForm",
        },
      ],
      deviceType: [
        { name: "新建报修", EntityType: "device", path: "/newRepair" },
        {
          name: "新建点巡检",
          EntityType: "device",
          path: "/inspectionTaskForm",
        },
        {
          name: "新建保养",
          EntityType: "device",
          path: "/devicesCare/maintenanceTasksAdd",
        },
      ],
      PDACode: "",
      autoFocus: false,
    };
  },
  computed: {
    path() {
      return this.$route.path;
    },
    current() {
      return this.tabs.findIndex((item) => item.path === this.path);
    },
  },
  mounted() {
    // Vue.use(VueCordova)
    // setTimeout(() => {
    //   this.$refs.PDAScan.focus();
    // }, 200);
  },
  methods: {
    // PDA扫码输入框聚焦时不调用手机键盘
    blurscan() {
      this.$refs.PDAScan.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.PDAScan.removeAttribute("readonly");
      }, 200);
    },
    // PDA扫码
    inputscan(v) {
      var str = v.target.value;
      var startStr = str.indexOf("{");
      var endStr = str.indexOf("}");
      var jsonStr = str.substring(startStr, str.length);
      if (startStr != -1 && endStr != -1) {
        var objByStr = eval("(" + jsonStr + ")");
        this.codeForm.code = objByStr;
        if (this.codeForm.code.EntityType == "batchCode") {
          queryBatchTaskReportList({ batchId: this.codeForm.code.id }).then(
            (res) => {
              if (res.success && res.result.length > 0) {
                this.$router.push({
                  path: "/batchReport",
                  query: {
                    code: this.codeForm.code,
                  },
                });
              } else {
                this.$toast("当前批次无可报工信息");
              }
            }
          );
          return;
        } else {
          this.$toast("请扫正确二维码");
        }
      }
    },
    go(index) {
      // if (index == 2) {
      //   this.clickCode();
      // } else {
        this.$router.push({
          path: this.tabs[index].path,
        });
      // }
    },
    // 打开相机
    clickCode() {
      let that = this;
      let platform = localStorage.getItem("currentEnvironment");
      console.log("??????", platform);
      switch (platform) {
        case "iwork":
          console.log("iwork扫码");
          var opt = {
            success: function(res) {
              console.log(JSON.stringify(res), "APP扫码数据");
              if (res.retCode == 0) {
                that.onDecode(res.retData);
              } else {
                that.$toast(res.retMsg);
              }
            },
            fail: function(err) {
              that.$toast("扫码失败！");
            },
          };
          //插件调用代码
          WorkHelper.scan(opt);
          break;
        case "browser":
          console.log("browser扫码");
          // camera:: 'front'--前摄像头，'rear'后摄像头，'off'关闭摄像头，会获取最后一帧显示，'auto'开始获取摄像头
          that.codeForm.qrcode = true;
          that.camera = "rear";
          // Vue.cordova.on("deviceready", () => {
          //   const scanOption = {
          //     preferFrontCamera: false, // iOS and Android
          //     showFlipCameraButton: true, // iOS and Android
          //     showTorchButton: true, // iOS and Android
          //     torchOn: false, // Android, launch with the torch switched on (if available)
          //     saveHistory: false, // Android, save scan history (default false)
          //     prompt: "在扫描区域内放置条形码", // Android
          //     resultDisplayDuration: 0, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
          //     formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
          //     // orientation : "landscape", // Android only (portrait|landscape), default unset so it rotates with the device
          //     disableAnimations: true, // iOS
          //     disableSuccessBeep: false, // iOS and Android
          //   };
          //   //扫描二维码
          //   window.cordova.plugins.barcodeScanner.scan(
          //     (result) => {
          //       that.onDecode(result.text);
          //     },
          //     (error) => {
          //       console.err(error);
          //     },
          //     scanOption
          //   );
          // });
          break;
        case "dingding":
          console.log("dingding扫码");
          dd.biz.util.scan({
            type: "qrCode", // type 为 all、qrCode、barCode，默认是all。
            onSuccess: function(data) {
              //onSuccess将在扫码成功之后回调
              that.onDecode(data.text);
              console.log(data);
            },
            onFail: function(err) {
              // console.error(err,'error')
            },
          });
          break;
        default:
          "";
          break;
      }
    },
    goType(t) {
      if (t.EntityType != this.codeForm.code.EntityType) {
        this.$toast("请扫正确二维码");
        this.showType = false;
        return;
      }

      if (t.name == "新建报工") {
        workOrderListProduce({ id: this.codeForm.code.id }).then((res) => {
          if (res.code == 200) {
            if (res.result.records[0].orderStatus != 1) {
              this.$toast("工单状态不正确");
              this.showType = false;
              return;
            } else {
              this.$router.push({
                path: t.path,
                query: {
                  code: this.codeForm.code,
                  formPage: "scanCode",
                },
              });
            }
          }
        });
      } else {
        this.$router.push({
          path: t.path,
          query: {
            code: this.codeForm.code,
            formPage: "scanCode",
          },
        });
      }
    },
    // 扫码结果回调
    onDecode(result) {
      // result, 扫描结果，可以根据自己的需求来实现相应的功能

      this.codeForm.code = JSON.parse(result);
      if (this.codeForm.code.EntityType == "batchCode") {
        console.log(this.codeForm.code, "this.codeForm.code");
        queryBatchTaskReportList({ batchId: this.codeForm.code.id }).then(
          (res) => {
            if (res.success && res.result.length > 0) {
              this.$router.push({
                path: "/batchReport",
                query: {
                  code: this.codeForm.code,
                },
              });
            } else {
              this.$toast("当前批次无可报工信息");
            }
          }
        );
        return;
      } else if (this.codeForm.code.EntityType == "workOrder") {
        // 工单二维码
        this.showType = true;
        this.codeTypes = this.orderType;
      } else if (this.codeForm.code.EntityType == "productTask") {
        // 任务二维码
        // this.showType = true;
        produceOrderReportWorkWorkbenchProduce({id:this.codeForm.code.id}).then((res) => {
          if (res.code == 200) {
            if (res.result.orderStatus != 1) {
              this.$toast("任务工单状态不正确");
              return;
            }else{
              this.$router.push({
                path: "/newReportForm",
                query: {
                  code: this.codeForm.code,
                  codeType:'productTask'
                },
              });
            }
          } 
        });
      } else if (this.codeForm.code.EntityType == "goods") {
        // 物品二维码
        this.showType = true;
        this.codeTypes = this.goodsType;
      } else {
        this.$toast("请扫正确二维码");
        this.clickCode();
      }
      console.log(result, "扫码结果");
    },
    // 相机反转
    switchCamera() {
      switch (this.camera) {
        case "front":
          this.camera = "rear";
          break;
        case "rear":
          this.camera = "front";
          break;
        default:
          this.$toast("错误");
      }
    },
    // 关闭相机
    turnCameraOff() {
      this.camera = "off";
      this.codeForm.qrcode = false;
    },
    // 打开手电筒
    ClickFlash() {
      switch (this.torchActive) {
        case true:
          this.torchActive = false;
          break;
        case false:
          this.torchActive = true;
          break;
        default:
          this.$toast("错误");
      }
    },

    // 检查是否调用摄像头
    async onInit(promise) {
      try {
        await promise;
      } catch (error) {
        if (error.name === "StreamApiNotSupportedError") {
        } else if (error.name === "NotAllowedError") {
          this.errorMessage = "Hey! I need access to your camera";
        } else if (error.name === "NotFoundError") {
          this.errorMessage = "Do you even have a camera on your device?";
        } else if (error.name === "NotSupportedError") {
          this.errorMessage =
            "Seems like this page is served in non-secure context (HTTPS, localhost or file://)";
        } else if (error.name === "NotReadableError") {
          this.errorMessage =
            "Couldn't access your camera. Is it already in use?";
        } else if (error.name === "OverconstrainedError") {
          this.errorMessage =
            "Constraints don't match any installed camera. Did you asked for the front camera although there is none?";
        } else {
          this.errorMessage = "UNKNOWN ERROR: " + error.message;
        }
      }
    },
  },
};
</script>
<style lang="scss">
[class*="van-hairline"]::after {
  border: none !important;
}
.van-toast {
  z-index: 99999 !important;
}
.tabbar {
  // height: 0.rem !important;
  box-shadow: 0px -6px 10px 0px rgba(161, 177, 198, 0.05);
  .item {
    .icon {
      width: 44px;
    }
    .iconcenter {
      width: 80px;
      transform: translateY(-16px);
      z-index: 666;
      border: 14px solid #fff;
      border-radius: 50%;
      box-sizing: content-box;
    }
    .tabLabel {
      margin-top: 4px;
      font-size: 18px;
      color: #888;
      &.selected {
        color: #4c87f9;
        background: none;
      }
    }
  }
}
.van-tabbar--fixed {
  z-index: 99999 !important;
}
.btn-wrapper {
  width: 100%;
  max-height: 50%;
  overflow-y: scroll;
  position: absolute;
  bottom: 0;
  padding: 10px;
  font-family: PingFang-SC-Medium;
  font-size: 32px;
  .type-btn {
    border-radius: 6px;
    background: #fff;
    .typebs {
      padding: 24px 0;
      text-align: center;
    }
    .typebs:nth-child(n + 2) {
      border-top: #f0f0f0 solid 2px;
    }
  }
}
.tabBox {
  height: 10px;
  .van-overlay {
    z-index: 100000 !important;
  }
}
</style>
